#!/usr/bin/env python

import hashlib
import re
import sessionManager
import pickle

"""
File:       bbs.py
Author:     Jkuhn

Description: This is the backend implementation of the BBS System

Interfaces:
            getData() 
                - returns a dict of this server's own data 
            addData(dataDict, serverName)
                - give this server data from another server
                - supercededs any existing data from that server
                - does not change or corrupt the result of getData().           
            purge(serverName)
                - purges all entries associated with the specified serverName
                - does not change or corrupt the result of getData()
            query(userData)
                - This is where any data (other than a login) should be passed
                - Returns a response to that query
                - Should not fail or crash the system under any circumstance
            login(user, pass)
                - Check to see if a user has a valid account on the system
                - Uses the passFile passed in as an __init__ arg.
                - Returns a bool indicating success or failure
"""

class bbs:
    def __init__(self, dataFile="messages.txt", passFile=".passwd"):
        self.dataFile = dataFile
        self.passFile = passFile

        # validate arguments
        try:
            dtest = open(dataFile, 'r')          
            dtest.close() 
        except:
            print "ERROR: Could not open dataFile"
        try:
            ptest = open(passFile, 'r')
            ptest.close()
        except:
            print "ERROR:  Could not open passFile"

        self.manager = sessionManager.sessionManager("messages.txt")
        # other setup code here


    def getData(self):
        """ returns a list of this server's data """
        tmpObj = repr(self.manager.bbsData)
        #print "Repr from bbs.py is " + tmpObj
        return tmpObj


    def addData(self, data, serverName):
        """ add data from another server to this bbs server """
        #print "This is the data before eval " + data
        tempObj = eval(data)
        #print "This is the data to add " + str(tempObj)
        self.manager.addForeignData(tempObj, serverName)


    def purge(self, serverName):
        """ purge all messages from a specified server """
        if self.manager == None:
            print "ERROR:  Manager was none"   
        self.manager.purge(serverName)     
        


    def query(self, userName, userData):
        """ 
        This is the entry point for all non-login data from a user
        it will always have a response.  It will never cause an exception
        """
        print "Unstripped input from Codi:", userName, userData 
        return self.manager.handleInput(userName.rstrip(), userData.rstrip())
        

    def login(self, user, password):
        """ 
        Take a plain text username and password.  Hash the password
        then compare the user:pass string to a file of user:pass strings.
        """
        user = user.rstrip()
        password = password.rstrip() # UGH.. well that's embarrassing.
        
        print "INFO: BBS Login user: '" + user + "'"
        print "INFO: BBS Login pass: '" + password + "'"
        
        hashedPwd = hashlib.sha256(password).hexdigest()
        userPassStr = user + ":" + hashedPwd

        pfile = open(self.passFile, 'r')
        for line in pfile.readlines():
            if re.match(userPassStr, line):
                pfile.close()
                return True
        # no match found in password file
        pfile.close()
        return False
        
    
    
